#
# Uploader.py
#

from qt import *
from kdecore import *
from kio import *
import os, base64
from Utils.PListParser import *
from BinaryUploader import *
from DB.Library import *

class LMusicSyncer(QObject):
	def __init__(self):
		QObject.__init__(self)
		self.queue = []
		self.currentJob = None
		self.currentIO = None
	
	def syncLibraries(self,remoteLibrary,localLibrary):
		if len(self.queue)==0:
				self.status({'Source':'Syncer','Status':'Begin'});
				self.total = 0
				self.index = 0
		tracks = localLibrary.tracks().values()
		for track in tracks:
			self.queue.append({'Track':track,'Library':localLibrary,'Remote Library':remoteLibrary})
		self.total = self.total+len(tracks)
		self.syncNextTrack()
	
	def status(self,status):
		self.emit(PYSIGNAL("status"),(status,None))

	def syncNextTrack(self):
		if self.currentJob==None:
			if len(self.queue)!=0:
				self.index = self.index+1 
				self.currentItem = self.queue[0]
				self.queue = self.queue[1:]
				self.track = self.currentItem['Track']
				self.library = self.currentItem['Library']
				self.remoteLibrary = self.currentItem['Remote Library']
				#print "syncing",self.track,"from",library,"with",remoteLibrary
				url = self.remoteLibrary.url()+"haveTracks"
				kurl = KURL(url)
				data = PListWriter().unparseToString([{'Version':'1.0','Tracks':[self.track.getPList()]}])+"\n\n"
				self.currentJob = KIO.http_post(kurl,data,False)
				self.currentJob.addMetaData("content-type","text/xml")
				self.currentJob.addMetaData("content-length",str(len(data)))
				QObject.connect(self.currentJob,SIGNAL('data(KIO::Job *,const QByteArray &)'),self.onData)
				QObject.connect(self.currentJob,SIGNAL('result(KIO::Job *)'),self.onResult)
				self.currentJob.result = ""
				self.status({'Source':'Syncer','Status':'Syncing','currentTime':self.index,'totalTime':self.total,'Track':self.track})
				self.currentJob.resume()
			else:
				print "syncing complete"
				self.status({'Source':'Syncer','Status':'End'})
		else:
			print "syncer busy"

	def onData(self,job,bytes):
		self.currentJob.result = self.currentJob.result+str(bytes)

	def onResult(self,job):
		#print "done sync test"
		try:
			plist = PListReader().parseString(self.currentJob.result)[0]
			for item in plist['Tracks']:
				try:
					if not item['Found']:
						track = Library.mainLibrary().trackWithTrackID(item['Track ID'])
						if track:
							LMusicBinaryUploader.singleton().uploadTracks([track],None,self.remoteLibrary)
						#print "uploading local trackID",track.trackID
					#else: print "track found"
				except: pass
		except: pass
		self.currentJob = None
		self.syncNextTrack()

	def static_singleton():
		global _musicSyncerSingleton
		if _musicSyncerSingleton==None:
			_musicSyncerSingleton = LMusicSyncer()
		return _musicSyncerSingleton
	
	singleton = staticmethod(static_singleton)

_musicSyncerSingleton = None
